package com.menggudf;

import com.github.pagehelper.util.StringUtil;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.constraints.NotNull;
import java.io.ByteArrayInputStream;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStream;

public class ByteToMultipartFileConverterUtil {
 
    private ByteToMultipartFileConverterUtil() {
    }
 
public static MultipartFile convert(byte[] pdfBytes, String fileName) {
        InputStream inputStream = new ByteArrayInputStream(pdfBytes);
        return new MultipartFile() {
            @NotNull
            @Override
            public String getName() {
                return "file";
            }
 
            @Override
            public String getOriginalFilename() {
                return StringUtil.isEmpty(fileName) ? "file.pdf" : fileName;
            }
 
            @Override
            public String getContentType() {
                return "application/pdf";
            }
 
            @Override
            public boolean isEmpty() {
                return pdfBytes.length == 0;
            }
 
            @Override
            public long getSize() {
                return pdfBytes.length;
            }
 
            @NotNull
            @Override
            public byte[] getBytes() {
                return pdfBytes;
            }
 
            @NotNull
            @Override
            public InputStream getInputStream() {
                return inputStream;
            }
 
            @Override
            public void transferTo(@NotNull java.io.File file) throws IllegalStateException {
                throw new UnsupportedOperationException("MultipartFiles must not be manually written to disk");
            }
        };
    }
 
 
 
public static byte[] inputStreamToByteArray(InputStream inputStream) throws IOException {
        // 使用 DataInputStream 包装 InputStream
        DataInputStream dis = new DataInputStream(inputStream);
        // 获取 InputStream 的数据长度
        int length = inputStream.available();
        // 创建 byte[] 数组，存储 InputStream 的数据
        byte[] bytes = new byte[length];
        // 读取 InputStream 中的数据并存储到 byte[] 数组中
        dis.readFully(bytes);
        return bytes;
    }


    public static void main(String[] args) {
        MultipartFile convert = convert(StringToHtmlConverter.str.getBytes(), "/Users/zengqd/Desktop/临时文件/");
        System.out.println(convert);
    }
}
